﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Caching.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel;
using Microsoft.Practices.EnterpriseLibrary.Caching;
using System.ComponentModel;
using System.Configuration;

namespace EntlibCacheStorage
{
    /// <summary>
    /// Sqlite 缓存配置
    /// </summary>
    [Browsable(true)]
    public class CustomCacheStorageData : CacheStorageData
    {
        private const string partitionNameProperty = "partitionName";
        private const string storageHandleTypeProperty = "storageHandleType";

        private Type _storagehandleType;

        public CustomCacheStorageData()
            : base(typeof(CustomDataBackingStore))
        {

        }
        public CustomCacheStorageData(string name, string partitionName, string storageHandleTypeName)
            : base(name, typeof(CustomDataBackingStore))
        {
            this.PartitionName = partitionName;
            this.StorageHandleTypeName = storageHandleTypeName;

            _storagehandleType = Type.GetType(storageHandleTypeName, true, true);
        }

        /// <summary>
        /// 分区
        /// </summary>
        [ConfigurationProperty(partitionNameProperty, IsRequired = true)]
        public string PartitionName
        {
            get { return (string)base[partitionNameProperty]; }
            set { base[partitionNameProperty] = value; }
        }

        /// <summary>
        /// 存储程序 ICacheDataStore
        /// </summary>
        [ConfigurationProperty(storageHandleTypeProperty, IsRequired = true)]
        public string StorageHandleTypeName
        {
            get { return (string)base[storageHandleTypeProperty]; }
            set { base[storageHandleTypeProperty] = value; }
        }

        public override IEnumerable<TypeRegistration> GetRegistrations()
        {
            var storagehandle = Activator.CreateInstance(_storagehandleType) as ICacheDataStore;
            var instance = new TypeRegistration<IBackingStore>(
                () => new CustomDataBackingStore(storagehandle, PartitionName))
            {
                Name = this.Name
            };
            yield return instance;
        }
    }
}
